package com.atguigu.day07;

import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

public class Flink07_OperatorState_BroadcastState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.分别获取两条流
        DataStreamSource<String> localStream = env.socketTextStream("localhost", 9999);
        DataStreamSource<String> hadoopStream = env.socketTextStream("hadoop102", 9999);

        //3.广播本地流
        MapStateDescriptor<String, String> mapstate = new MapStateDescriptor<>("mapstate", String.class, String.class);
        BroadcastStream<String> broadcastStream = localStream.broadcast(mapstate);

        //4.链接两条流
        BroadcastConnectedStream<String, String> broadcastConnectedStream = hadoopStream.connect(broadcastStream);

        //5.通过一条流控制另外一条流的逻辑
        broadcastConnectedStream.process(new BroadcastProcessFunction<String, String, String>() {
            @Override
            public void processElement(String value, ReadOnlyContext ctx, Collector<String> out) throws Exception {
                //1.提取广播状态
                ReadOnlyBroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapstate);

                //2.读取广播流中的数据然后通过不同的数据来决定逻辑
                if ("1".equals(broadcastState.get("switch"))) {
                    out.collect("执行逻辑1.。。。。。");
                } else if ("2".equals(broadcastState.get("switch"))) {
                    out.collect("执行逻辑2.。。。。。");
                } else {
                    out.collect("执行其他逻辑");
                }

            }

            @Override
            public void processBroadcastElement(String value, Context ctx, Collector<String> out) throws Exception {
                //1.提取广播状态
                BroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapstate);
                //2.将本地流中的数据放到广播状态中
                broadcastState.put("switch", value);
            }
        }).print();


        env.execute();
    }
}
